#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""App to record user actions in a database, and generate reports"""

from string import Template
import time

from tack.lib import json_app
from tack.db import query, sql_string
from tack.lib.dicttools import rows_to_dicts

insert_access = """
INSERT INTO tack_usertracking
(login, url, method, request_time, ip)
VALUES
($user, $path, $method, $time, $ip)
"""

query_access = """
SELECT $distinct login, url, method, request_time, ip
FROM tack_usertracking
WHERE $where
ORDER BY usertracking_id
"""

def usertracking(app, verbose=False, db_key='connection'):
    """
    Creates and returns an app to track user actions

    Must be wrapped with an app that provides a database connection in the given
    environ key.
    """
    def tracker(env, start_response):
        con = env[db_key]
        sql = Template(insert_access).substitute({
            'user': sql_string(env['REMOTE_USER']),
            'path': sql_string(env['PATH_INFO']),
            'method': sql_string(env['REQUEST_METHOD']),
            'time': time.strftime('%Y-%m-%d %H:%M:%S %Z'),
            'ip': sql_string(env['REMOTE_ADDR']),})
        query(con, sql)
        return app(environ, start_response)
    return tracker

def userhistory(db_key='connection',
                 login_path='/api/login/', logout_path='/api/logout/'):
    """
    Creates and returns an app to report on user actions

    Must be wrapped with an app that provides a database connection in the given
    environ key.
    """
    def history(env, start_response):
        con =  env[db_key]
        user_data = {}
        sql = Template(query_access).substitute({
            'distinct': '',
            'where': '1=1'})
        rows = rows_to_dicts(query(con, sql),
                             ('login', 'url', 'method', 'request_time', 'ip'))
        for row in rows:
            if row['login'] not in user_data:
                user_data[row['login']] = {'first_login': None,
                                             'last_login': '0000-00-00 00:00:00'
                                             }
                if row['url'] == login_path:
                    if not user_data[row['login']]['first_login']:
                        user_data[row['login']]['first_login'] = row['request_time']
                    if (row['request_time'] > user_data[row['login']]['last_login']):
                        user_data[row['login']]['last_login'] = row['request_time']
        return json_app(user_data)(env, start_response)
    return history